package com.suse.forum.service.impl;

import com.suse.forum.common.AppResult;
import com.suse.forum.common.ResultCode;
import com.suse.forum.dao.UserMapper;
import com.suse.forum.exception.ApplicationException;
import com.suse.forum.model.User;
import com.suse.forum.service.IUserService;
import com.suse.forum.utils.MD5Util;
import com.suse.forum.utils.StringUtil;
import com.suse.forum.utils.UUIDUtil;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        //1. 非空校验
        if(user == null || StringUtil.isEmpty(user.getUsername())
            || StringUtil.isEmpty(user.getNickname())
            || StringUtil.isEmpty(user.getPassword())
            || StringUtil.isEmpty(user.getSalt())) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常,统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));

        }

        //2. 按用户名查询用户信息
        User existsUser = userMapper.selectByUserName(user.getUsername());
        //2.1 判断用户是否存在
        if(existsUser != null) {
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        //3. 新增用户流程,设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        //当前日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        //写入数据库
        int row = userMapper.insertSelective(user);
        if(row != 1) {
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        log.info("新增用户成功, username = " + user.getUsername() + ". ");

    }

    @Override
    public User selectByUserName(String username) {
        // 非空检验
        if(StringUtil.isEmpty(username)) {
            // 打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 调用mapper查询
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        //1.非空校验
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            // 打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //2.按用户名查询用户信息
        User user = userMapper.selectByUserName(username);
        //3.对查询结果做非空校验
        if(user == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString() + ", username = " + username );
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //4.校验密码
        String encryptPassword = MD5Util.md5Salt(password, user.getSalt());
        //5.用密文和数据库中的密码进行比对
        if(!encryptPassword.equalsIgnoreCase(user.getPassword())) {
            // 打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString() + ",密码错误， username = " + username );
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //6.校验通过，返回用户信息
        log.info("登录成功 , username = " + username);
        return user;
    }

    @Override
    public User selectById(Long id) {
        //1.非空校验
        if(id == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO查询数据库并获取对象
        User user = userMapper.selectByPrimaryKey(id);
        //返回结果
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        //非空校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }

        //更新用户的发帖数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        //更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        //校验受影响的行数
        if(row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        //非空校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新用户的发帖数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        // 判断 - 1 后，用户的发帖数是否小于 0
        if(updateUser.getArticleCount() < 0) {
            // 如果小于 0 ， 则设置为 0
            updateUser.setArticleCount(0);
        }
        //更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        //校验受影响的行数
        if(row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        // 1.非空校验
        if(user == null || user.getId() == null || user.getId() <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 2.校验用户是否存在
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if(existsUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 3.定义一个标志位
        boolean checkAttr = false; // false 表示没有校验通过

        // 4.定义一个专门用来更新的对象，防止用户传入的User对象中设置了其他属性
        // 当使用动态SQl进行更新的时候，覆盖了没有经过校验的字段
        User updateUser = new User();
        // 5.设置用户ID
        updateUser.setId(user.getId());
        // 6.对每一个参数进行校验并赋值
        if(!StringUtils.isEmpty(user.getUsername()) && !user.getUsername().equals(existsUser.getUsername())) {
            // 如果用户名不为空，并且用户名和数据库中用户名不一致，则校验用户名是否已经存在(唯一性)
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if(checkUser != null) {
                // 用户已存在
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            // 数据库中没有找到相应的用户，表示可以修改用户名
            updateUser.setUsername(user.getUsername());
            // 更新标志位
            checkAttr = true;
        }

        // 7.校验昵称
        if(!StringUtils.isEmpty(user.getNickname()) && !user.getNickname().equals(existsUser.getNickname())) {
            // 设置昵称
            updateUser.setNickname(user.getNickname());
            // 更新标志位
            checkAttr = true;
        }

        // 8.校验性别
        if(user.getGender() != null && user.getGender() != existsUser.getGender()) {
            // 设置性别
            updateUser.setGender(user.getGender());
            // 合法性校验
            if(user.getGender() > 2 || updateUser.getGender() < 0) {
                updateUser.setGender((byte)2);
            }
            // 更新标志位
            checkAttr = true;
        }

        // 9.校验邮箱
        if(!StringUtils.isEmpty(user.getEmail()) && !user.getEmail().equals(existsUser.getEmail())) {
            // 设置邮箱
            updateUser.setEmail(user.getEmail());
            // 更新标志位
            checkAttr = true;
        }

        // 10.校验手机号
        if(!StringUtils.isEmpty(user.getPhoneNum()) && !user.getPhoneNum().equals(existsUser.getPhoneNum())) {
            // 设置手机号
            updateUser.setPhoneNum(user.getPhoneNum());
            // 更新标志位
            checkAttr = true;
        }

        // 11.校验个人简介
        if(!StringUtils.isEmpty(user.getRemark()) && !user.getRemark().equals(existsUser.getRemark())) {
            // 设置手机号
            updateUser.setRemark(user.getRemark());
            // 更新标志位
            checkAttr = true;
        }

        // 12.校验更新标志位
        if(checkAttr == false) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 13.更新用户信息
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String oldPassword, String newPassword) {
        // 非空校验
        if(id ==null || id <= 0 || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        // 校验用户是否存在
        if(user == null || user.getDeleteState() == 1) {
            // 用户不存在
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 校验旧密码是否正确
        // 对旧密码进行加密，获取密文
        String oldEncryptPassword = MD5Util.md5Salt(oldPassword, user.getSalt());
        // 与用户当前的密码进行比较
        if(!oldEncryptPassword.equalsIgnoreCase(user.getPassword())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 生成一个新的盐值
        String salt = UUIDUtil.UUID_32();
        // 对新密码进行加密，获取密文
        String encryptPassword = MD5Util.md5Salt(newPassword, salt);

        // 构造要更新的对象
        User updateUser = new User();
        updateUser.setId(user.getId()); // 用户ID
        updateUser.setSalt(salt); // 新生成的盐值
        updateUser.setPassword(encryptPassword); // 新密码的密文
        Date date = new Date();
        updateUser.setUpdateTime(date); // 更新时间

        // 调用DAO
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }
}
